package com.stsdai.serach.service.message;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stsdai.search.service.SearchService;
public class ItemMessageListener implements MessageListener {

	private static final ObjectMapper MAPPER = new ObjectMapper();

	@Autowired
	private SearchService searchService;

	@Override
	public void onMessage(Message message) {
		// 判断消息类型是否是TextMessage
		if (message instanceof TextMessage) {
			// 如果是，则强转
			TextMessage textMessage = (TextMessage) message;

			try {
				// 从消息体中获取消息内容{type:save,itemId:123}
				String json = textMessage.getText();

				if (StringUtils.isNotBlank(json)) {
					// 解析消息，获取操作符和商品id
					JsonNode jsonNode = MAPPER.readTree(json);

					// 操作符
					String type = jsonNode.get("type").asText();
					// itemId
					long itemId = jsonNode.get("itemId").asLong();

					// 根据消息内容，更新索引库商品数据
					// 判断是否是新增操作
					if ("save".equals(type)) {
						// 如果是新增，添加商品数据到索引库
						this.searchService.addItem(itemId);
					}

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
